﻿using Gdmec.Config;
using System;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using XLua;

namespace Gdmec.Lua
{
    /// <summary>
    /// xLua管理器
    /// </summary>
    public class LuaManager : MonoBehaviour
    {
        private LuaEnv env;
        public static LuaManager Instance { get; private set; }

        [Obsolete]
        void Awake()
        {
            Instance = this;
            
            Instance.env = new LuaEnv();
            Instance.env.AddLoader(addLoader);
        }

        [Obsolete]
        private byte[] addLoader(ref string filepath)
        {
            return GetFileBytes(filepath);
        }

        void OnDestroy()
        {
            Instance.env.StopGc();
            Instance.env.FullGc(); ;
            Instance.env = null;
            Instance = null;
        }

        [Obsolete]
        public static void DoLua(string file)
        {
            Instance.env.DoString(Instance.GetFileBytes(file));
        }

        private string path = "";

        [Obsolete]
        private byte[] GetFileBytes(string file)
        {

            //项目路径
            path = GameConfig.ToProjectPath(GameConfig.LuaScriptPath) + "/" + file;
            if (File.Exists(path))
            {
                return System.IO.File.ReadAllBytes(path); ;
            }

            //热更目录
            path = PathUtil.ToSame(GameConfig.ToHotFixPath(GameConfig.LuaScriptPath) + "/" + file);
            if (File.Exists(path))
            {
                return File.ReadAllBytes(path);
            }

            //流文件路径
            path = PathUtil.ToSame(GameConfig.ToStreamingAssetPath(GameConfig.LuaScriptPath) + "/" + file);
            WWW www = new WWW(path);
            while (!www.isDone) { }
            if (www.text != string.Empty)
            {
                return System.Text.Encoding.UTF8.GetBytes(www.text);
            }
            Debug.LogError(string.Format("lua error no find {0}", path));
            return null;
        }
    }
}